<template>
	<view :style="skin" class="content faultReporting">
		<view class="overdueList">
			<view class="overdueListLeft">
				<u--image shape="circle" :src="appearObj.photo" width="75px" height="75px"></u--image>
			</view>
			<view class="overdueListRight">
				<view class="rightTips">
					{{$t('lease.productModel')}}: {{appearObj.productModel}}
					<text class="iconfont icon-a-mingchengarrow_right iconRight" @click="handleDeviceType"></text>
				</view>
				<view class="rightTips">
					{{$t('lease.productID')}}: {{appearObj.productId}}
					<text class="iconfont icon-a-mingchengarrow_right iconRight" @click="handleDevice"></text>
				</view>
				<view class="rightTips">
					{{$t('property.faultType')}}: {{appearObj.faultName}}
					<text class="iconfont icon-a-mingchengarrow_right iconRight" @click="malShow = true"></text>
				</view>
				<view class="rightTips">
					{{$t('property.faultReporting')}}:{{getNewDate}}
				</view>

			</view>

		</view>
		<view class="mt16">
			problem description:
			<u--textarea v-model="appearObj.faultDetail" placeholder="Please enter" count></u--textarea>
		</view>
		<view class="mt16">
			Upload fault photos (up to four):
			<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
				:maxCount="4"></u-upload>
		</view>
		<view class="mt16">
		At least two, one with the product ID and one with the fault point
		</view>
		<view class="mt16">
			<u-button color="var(--subjectColor)" @click="submit">submit</u-button>
		</view>

		<view class="mySheet">
			<!-- 产品分类 -->
			<u-action-sheet @close="deviceTypeShow = false" @select="selectDeviceType" cancelText="cancel"
				:actions="deviceTypeList" :show="deviceTypeShow"></u-action-sheet>

			<!-- 产品信息 -->
			<u-action-sheet @close="deviceShow = false" @select="selectDevice" cancelText="cancel" :actions="deviceList"
				:show="deviceShow"></u-action-sheet>

			<!-- 故障类型 -->
			<u-action-sheet @close="malShow = false" @select="selectMal" cancelText="cancel" :actions="malList"
				:show="malShow"></u-action-sheet>
		</view>

	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	import {
		iconUpload
	} from '@/api/user.js'
	import {
		cloudmateURL
	} from '@/utils/requestURL.js'
	import {
		cameraAuthority
	} from '@/utils/jurisdiction.js'
	import {
		getNewYMD
	} from '@/utils/index.js'
	import {
		StockFaultModelList,
		faultReport
	} from '@/api/leaProductFault.js'
	import {
		addDevice,
		getDeviceTypeToId
	} from '@/utils/sql/sqlDevice.js'
	import {
		getDeviceType,
		reduceInsoter,
		reduceTenantable
	} from '@/utils/sql/sqlDeviceType.js'
	import {
		addLease,
		leaFaultStore
	} from '@/utils/sql/sqllease.js'

	const database = uni.getStorageSync('database')
	export default {
		data() {
			return {
				type: '', //入口类型
				URL1: '',
				fileList1: [],
				src: '',
				value1: '',
				appearObj: {},

				deviceTypeShow: false,
				deviceTypeList: [],

				deviceShow: false,
				deviceList: null,

				malShow: false,
				malList: [],

			};
		},
		onShow() {

			this.openDB()
		},
		async onLoad(options) {
			console.log(options);
			cameraAuthority()
			if (options.appearObj) {
				this.appearObj = JSON.parse(options.appearObj);
			}
			if (options.type == 'mal') {
				await this.getTypeList()

			}
			this.type = options.type
			this.faultModelList()

			// uni.$off('update_malList')
		},
		methods: {
			selectDeviceType(item) {
				console.log(item);
				this.appearObj.productModel = item.productModel
				this.getDeviceList(item.productModel)
			},
			selectDevice(item) {
				console.log(item);
				this.appearObj.productId = item.productId
			},
			selectMal(item) {
				console.log(item);
				this.appearObj.faultName = item.faultName
				this.appearObj.faultName = item.faultName
				this.appearObj.faultNameEn = item.faultNameEn
			},
			async openDB() {
				let res = await this.$sql.isOpen(database);
				if (res.data) return
				let res1 = await this.$sql.openDB(database);
			},
			getTypeList() {
				getDeviceType().then(res => {
					console.log(res);
					res.data.map(item => {
						return item.name = item.productModel
					})
					this.deviceTypeList = res.data
				})
			},
			getDeviceList(productModel) {
				getDeviceTypeToId(productModel).then(res => {
					let newArr = res.data.filter(item => {
						return item.stockStatus == 1 || item.stockStatus == 2 || item.stockStatus == 4 || item.stockStatus == 6
					})
					newArr.map(item => {
						return item.name = item.productId
					})
					this.deviceList = newArr
				})
			},
			submit() {

				if (!this.appearObj.productModel || !this.appearObj.productId || !this.appearObj.faultDetail) {
					uni.showToast({
						title: 'Parameter missing',
						icon: 'none'
					})
					return false
				}
				if (this.fileList1.length > 4) {
					uni.showToast({
						title: 'Up to four',
						icon: 'none'
					})
					return false
				}
				if (this.fileList1.length < 2) {
					uni.showToast({
						title: 'At least two',
						icon: 'none'
					})
					return false
				}
				uni.showLoading({
					title: 'Waiting',
				})


				let faultPhotos = this.fileList1.map(item => item.url).join(',')
				faultReport({
					productModel: this.appearObj.productModel,
					productId: this.appearObj.productId,
					faultCode: this.appearObj.faultCode,
					faultDetail: this.appearObj.faultDetail,
					faultPhotos: faultPhotos,
				}).then(async res => {
					console.log(res);
					uni.hideLoading()
					// 本地修改设备状态故障
					if (res.code == 0) {

						// 查询该设备并且是租赁中 或者逾期的 信息
						leaFaultStore(this.appearObj.productId).then(async rrs => {
							if (rrs.code == 0 && rrs.data.length > 0) {
								let len = rrs.data.length - 1;
								let appearObj = rrs.data[len]
								let leaObj = {
									leaseId: appearObj.leaseId,
									leaseStatus: 10,
									iSync: 0
								}
								await addLease(leaObj)

							} else {
								reduceInsoter(this.appearObj.productModel);
								reduceTenantable(this.appearObj.productModel);
							}
						})

						uni.showToast({
							title: 'Report successfully',
							icon: 'none'
						})

						let obj = {
							productId: this.appearObj.productId,
							stockStatus: 10
						}
						addDevice(obj).then(rrs => {
							if (this.type == 'return'){
								uni.$emit('lostBack');
							}else{
								uni.$emit('update_malList');
							}
							
							
							setTimeout(()=>{
									uni.navigateBack();
							},1000)
							
						})



					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			},
			faultModelList() {
				StockFaultModelList().then(res => {
					console.log(res);
					res.data.map(item => {
						return item.name = item.faultName
					})
					this.appearObj.faultCode = res.data[0].faultCode
					this.appearObj.faultName = res.data[0].faultName
					this.appearObj.faultNameEn = res.data[0].faultNameEn

					this.malList = res.data
				})
			},
			handleDeviceType() {
				if (this.type == 'return') return false
				this.deviceTypeShow = true
			},
			handleDevice() {
				console.log(this.deviceList);
				if (this.type == 'return') return false
				if (this.deviceList.length == 0) return false
				this.deviceShow = true
			},

			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			async afterRead(event) {
				let lists = [].concat(event.file)
				let fileListLen = this.fileList1.length
				lists.map((item) => {
					this.fileList1.push({
						...item,
						status: 'uploading',
						message: 'uploading'
					})
				})

				for (let i = 0; i < lists.length; i++) {

					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.fileList1[fileListLen]
					this.fileList1.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}

			},
			async uploadFilePromise(url) {
				console.log(url);
				let res = await iconUpload(url)
				let rrs = JSON.parse(res)
				if (rrs.code == 0) {
					console.log(cloudmateURL + rrs.data.url);

					return cloudmateURL + rrs.data.url
				}
			},
		},

		computed: {
			...mapState({
				skin: state => state.theme.skin
			}),
			getNewDate() {
				return getNewYMD()
			}

		},
	}
</script>

<style lang="scss" scoped>
	.faultReporting {
		padding: 16px;
		box-sizing: border-box;

		.overdueList {
			width: 100%;
			padding: 16px 0;
			box-sizing: border-box;
			height: 120px;
			display: flex;
			background-color: #fff;
			border: 1px solid #ccc;
			margin-bottom: 8px;

			.overdueListLeft {
				width: 102px;
				height: calc(100% - 16px);
				margin-top: 8px;
				border-right: 1px solid #ccc;
				display: flex;
				flex-direction: column;
				align-items: center;

				.leftTips {
					width: 96px;

				}
			}

			.overdueListRight {
				font-size: 14px;
				color: #101010;
				padding-left: 16px;
				box-sizing: border-box;
				position: relative;
				width: 200px;

				.iconCheck {
					position: absolute;
					top: 50%;
					right: -40px;
					transform: translate(-50%, -50%);
				}

				.actionIcon {
					color: #4080FF;
				}

				.unActionIcon {
					color: #ccc;
				}

				.rightTips {
					line-height: 22px;
					width: 100%;

					.iconRight {
						float: right;
					}
				}
			}
		}

		.mt16 {
			margin-top: 16px;
		}
	}
</style>